﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Publicuse.DBCore.Redis.CMultiplexer.Interface;
using Publicuse.Util.Redis;

namespace Publicuse.DBCore.Redis.CMultiplexer.Service
{
    /// <summary>
    /// 哈希数据操作工具类
    /// </summary>
    public sealed class CMultiplexerHashService : CMultiplexerBase
    {
        public CMultiplexerHashService(int conIndex,int dbIndex)
            : base(conIndex,dbIndex)
        {
        }

        #region 添加
        /// <summary>
        /// 向hashid集合中添加key/value
        /// </summary>       
        public bool SetEntryInHash(string hashid, string key, string value)
        {
            return base.dbClient.HashSet(hashid, key, value);
        }
        /// <summary>
        /// 判断key是否存在
        /// </summary>
        public bool SetEntryInHashIfNotExists(string hashid, string key)
        {
            return base.dbClient.HashExists(hashid, key);
        }
        /// <summary>
        /// 存储对象T t到hash集合中
        /// </summary>
        public void StoreAsHash<T>(string key,T t)
        {
            ITransaction trans = base.dbClient.CreateTransaction();
            HashEntry[] val = null;
            RedisTools.ObjectToHashEntrys(t, out val);
            trans.HashSetAsync(key, val);
        }
        #endregion

        #region 获取
        /// <summary>
        /// 获取所有hashid数据集的key/value数据集合
        /// </summary>
        public Dictionary<string, string> GetAllEntriesFromHash(string key)
        {
            Dictionary<string, string> data = new Dictionary<string, string>();
            var list = base.dbClient.HashGetAll(key);
            foreach (var item in list)
            {
                data.Add(item.Name, item.Value);
            }
            return data;
        }

        /// <summary>
        /// 转换成对象
        /// </summary>
        /// <param name="kye"></param>
        /// <returns></returns>
        public T GetAllBykey<T>(string key)
        {
            T entity = default(T);
           var data= base.dbClient.HashGetAll(key);
            RedisTools.HashEntrysToObject<T>(data, out entity);
            return entity;
        }

        /// <summary>
        /// 获取对应Key的Value
        /// </summary>
        /// <param name="key"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public string GetValuByKey(string key,string name)
        {
            return base.dbClient.HashGet(key, name).ToString();
        }
       
        #endregion

        #region 删除
        /// <summary>
        /// 删除hashid数据集中的key数据
        /// </summary>
        public bool RemoveEntryFromHash(string hashid, string key)
        {
            return base.dbClient.HashDelete(hashid, key);
        }
        #endregion
    }
}
